package com.boil.qz.safekavass.weixin.controller;

import com.boil.exception.RequestParamException;
import com.boil.pojo.ResultVo;
import com.boil.qz.safekavass.model.ReportRes;
import com.boil.qz.safekavass.pojo.ReportResVo;
import com.boil.qz.safekavass.service.ReportResService;
import com.boil.qz.safekavass.web.request.param.IdParam;
import com.boil.qz.safekavass.weixin.request.param.AddReportResParam;
import com.boil.qz.safekavass.weixin.request.param.ReportResListParam;
import com.boil.qz.safekavass.weixin.util.WeixinUtils;
import com.boil.util.BaseController;
import com.boil.util.Constants;
import com.boil.util.Page1;
import com.boil.util.Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by ChenYong on 2017-04-24.
 * <br>
 * 举报 Controller。
 */
@Controller("reportResController2")
@RequestMapping("/weixin/report")
public class ReportResController extends BaseController {
    /**
     * 注入举报 Service
     */
    @Autowired
    private ReportResService reportResService;

    /**
     * 添加举报。
     *
     * @param model  模型
     * @param param  添加举报的请求参数
     * @param errors 请求参数的校验结果
     * @return 结果页面
     */
    @RequestMapping(method = RequestMethod.POST, value = "/add.html")
    public String add(Model model, @Valid AddReportResParam param, BindingResult errors) {
        // 结果 Vo
        ResultVo resultVo = new ResultVo();

        model.addAttribute(Constants.RESULT_VO, resultVo);

        try {
            // 判断请求参数是否校验通过
            Utils.hasRequestParamError(resultVo, errors);

            // 创建举报实例
            ReportRes reportRes = new ReportRes();
            reportRes.setOpenid(param.getOpenid());
            reportRes.setReportCreatePerson(param.getReportCreatePerson());
            reportRes.setReportName(param.getReportName());
            reportRes.setReportContent(param.getReportContent());
            reportRes.setReportSource(param.getReportSource());
            reportRes.setReportImages(param.getReportImages());
            reportRes.setReportResult(Constants.REPORT_RESULT_1);
            reportRes.setReportCreateTime(new Date());

            // 保存举报
            reportResService.saveReportRes(Constants.ID_1, reportRes);

            resultVo.setResultMsg("恭喜您，举报成功，等待管理员审核！");
        } catch (RequestParamException e) {
            resultVo = e.getResultVo();
            resultVo.setResultMsg(String.format("抱歉，举报失败，原因：%s", e.getMessage()));
        } catch (Exception e) {
            log.error("微信举报出现异常：{}", e);

            resultVo.setResultCode(Constants.SYS_ERROR);
            resultVo.setResultMsg(String.format("抱歉，举报失败，原因：%s", e.getMessage()));
        }

        resultVo.setResult(String.format(WeixinUtils.URL_CONNECT_OAUTH2_AUTHORIZE, //
                WeixinUtils.APP_ID, //
                Constants.URL_ENCODE_WEIXIN_WEBPAGE_AUTHORIZE_SNSAPI_USERINFO, //
                WeixinUtils.SCOPE_SNSAPI_USERINFO, //
                Constants.PAGE_REPORT));

        return "/weixin/result";
    }

    /**
     * 获取举报列表 json。
     *
     * @param model  模型
     * @param param  举报列表的请求参数
     * @param errors 请求参数的校验结果
     * @return 举报列表 json
     */
    @RequestMapping(method = RequestMethod.GET, value = "/list.json")
    @ResponseBody
    public ResultVo listJson(Model model, @Valid ReportResListParam param, BindingResult errors) {
        // 结果 Vo
        ResultVo resultVo = new ResultVo();

        try {
            // 判断请求参数是否校验通过
            Utils.hasRequestParamError(resultVo, errors);

            // 排序方式
            List<String> orderBys = new ArrayList<String>();
            orderBys.add("REPORT_CREATE_TIME DESC");

            // 分页实例
            Page1<ReportResVo> page1 = new Page1<ReportResVo>(Constants.PAGE_SIZE_20, param.getPage());
            page1.getParams().put(WeixinUtils.OPENID_STR, param.getOpenid());
            page1.getParamss().put(Constants.ORDER_BY_STR, orderBys);

            // 分页查询
            reportResService.findInPageByOpenid(page1);

            resultVo.setResult(page1);
        } catch (RequestParamException e) {
            resultVo = e.getResultVo();
        } catch (Exception e) {
            log.error("获取微信举报列表出现异常：{}", e);

            resultVo.setResultCode(Constants.SYS_ERROR);
            resultVo.setResultMsg(e.getMessage());
        }

        return resultVo;
    }

    /**
     * 获取举报详细页面。
     *
     * @param model  模型
     * @param param  ID 参数
     * @param errors 请求参数的校验结果
     * @return 举报详细页面
     */
    @RequestMapping(method = RequestMethod.GET, value = "/detail.html")
    public String detailHtml(Model model, @Valid IdParam param, BindingResult errors) {
        // 结果 Vo
        ResultVo resultVo = new ResultVo();

        model.addAttribute(Constants.RESULT_VO, resultVo);

        try {
            // 判断请求参数是否校验通过
            Utils.hasRequestParamError(resultVo, errors);

            // 获取举报
            ReportRes reportRes = reportResService.findById(param.getId());

            // 美化内容
            if (StringUtils.isNotBlank(reportRes.getReportContent())) {
                reportRes.setReportContent(reportRes.getReportContent()
                        .replaceAll(Constants.CONTENT_NEWLINE_RN_RE, Constants.CONTENT_NEWLINE_BR_SPAN)
                        .replaceAll(Constants.CONTENT_NEWLINE_N_RE, Constants.CONTENT_NEWLINE_BR_SPAN)
                        .replaceAll(Constants.CONTENT_NEWLINE_BR_SPAN_RE, Constants.CONTENT_NEWLINE_BR_SPAN)
                        .replaceAll(Constants.CONTENT_NEWLINE_SHIT_RE, Constants.EMPTY_STR));
            }

            resultVo.setResult(reportRes);

            return "/weixin/report/detail";
        } catch (RequestParamException e) {
            resultVo = e.getResultVo();
        } catch (Exception e) {
            log.error("获取举报详细出现异常：{}", e);

            resultVo.setResultCode(Constants.SYS_ERROR);
            resultVo.setResultMsg(e.getMessage());
        }

        resultVo.setResult(null);

        return "/weixin/result";
    }
}